package tp.tecnicasdisenio.dao.impl.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import tp.tecnicasdisenio.dao.AlumnoDaoInterface;
import tp.tecnicasdisenio.dao.DaoException;
import tp.tecnicasdisenio.model.entity.Alumno;
import tp.tecnicasdisenio.model.entity.Cuatrimestre;
import tp.tecnicasdisenio.model.entity.Materia;
import tp.tecnicasdisenio.util.FechaUtil;

public class AlumnoDao extends DaoAbstract implements AlumnoDaoInterface{

	private static AlumnoDao instancia = null;
	
	private String nombreTabla = "alumnos", atributoId = "padron";
	
	private AlumnoDao(){}
	
	public static AlumnoDao getInstance(){
		if (instancia == null)
			instancia = new AlumnoDao();
		return instancia;
	}

	private ArrayList<Alumno> obtenerAlumno(String id, boolean unoSolo) {
		ArrayList<Alumno> resultado = null;
		
		try {
			String queryString = "SELECT * FROM " + this.nombreTabla;
			
			if (unoSolo)
				queryString = queryString.concat(" WHERE " + this.atributoId + "=?");

			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			if (unoSolo)
				preparedStatement.setString(1, id);
			
			resultSet = preparedStatement.executeQuery();
			
			resultado = new ArrayList<Alumno>();
			Alumno alumnoDB = null;
			
			while (resultSet.next()) {
				alumnoDB = new Alumno();
				alumnoDB.setPadron(((Integer) resultSet.getInt("padron")).toString());
				alumnoDB.setNombre(resultSet.getString("nombre"));
				alumnoDB.setApellido(resultSet.getString("apellido"));
				alumnoDB.setEmail(resultSet.getString("email"));
				resultado.add(alumnoDB);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultado;
	}
	
	@Override
	public Alumno getPorId(String id) {
		ArrayList<Alumno> listaAlumnos = this.obtenerAlumno(id, true); 
		Alumno alumnoDB = null;
		if (!listaAlumnos.isEmpty())
			alumnoDB = listaAlumnos.iterator().next();
		return alumnoDB;
	}

	@Override
	public ArrayList<Alumno> obtenerTodos() {
		return (this.obtenerAlumno("", false));
	}

	@Override
	public void borrar(Alumno entidad) {				
		try {
			String queryString = "DELETE FROM " + this.nombreTabla + " WHERE " + this.atributoId + "=?";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setInt(1, new Integer(entidad.getPadron()));
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void actualizar(Alumno entidad) {				
		try {
			String queryString = "UPDATE " + this.nombreTabla + " SET nombre=?, apellido=?, email=? WHERE " + this.atributoId + "=?";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, entidad.getNombre());
			preparedStatement.setString(2, entidad.getApellido());
			preparedStatement.setString(3, entidad.getEmail());
			preparedStatement.setInt(4, new Integer(entidad.getPadron()));
			
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void insertar(Alumno entidad) {
		try {
			String queryString = "INSERT INTO " + this.nombreTabla + "(padron, nombre, apellido, email) VALUES(?,?,?,?)";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setInt(1, new Integer(entidad.getPadron()));
			preparedStatement.setString(2, entidad.getNombre());
			preparedStatement.setString(3, entidad.getApellido());
			preparedStatement.setString(4, entidad.getEmail());
						
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Alumno getPorEmail(String email) {
		Alumno alumnoDB = null;
		try {
			String queryString = "SELECT * FROM " + this.nombreTabla + " WHERE email=?";
			
			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			preparedStatement.setString(1, email);
			
			resultSet = preparedStatement.executeQuery();
			
			if (resultSet.next()) {
				alumnoDB = new Alumno();
				alumnoDB.setPadron(((Integer) resultSet.getInt("padron")).toString());
				alumnoDB.setNombre(resultSet.getString("nombre"));
				alumnoDB.setApellido(resultSet.getString("apellido"));
				alumnoDB.setEmail(resultSet.getString("email"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return alumnoDB;
	}

	@Override
	public boolean existeAlumnoConPadronOEmailDe(Alumno alumno) {
		boolean resultado = false;
		
		ArrayList<Alumno> alumnoDB = this.obtenerAlumno(alumno.getId(), true);
		
		if ((alumnoDB != null) && (alumnoDB.iterator().next().getEmail().compareTo(alumno.getEmail()) == 0))
			resultado = true;

		return resultado;
	}

	@Override
	public boolean estaInscriptoEnMateria(Alumno alumno, Materia materia, Cuatrimestre cuatrimestre) {
		boolean resultado = false;
		try {
			String queryString = "SELECT * FROM cursa WHERE padron=? AND codigo_materia=? AND cuatrimestre=? AND anio=?";
			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			preparedStatement.setInt(1, new Integer(alumno.getPadron()));
			preparedStatement.setString(2, materia.getCodigo());
			preparedStatement.setInt(3, new Integer(cuatrimestre.getCuatrimestre()));
			preparedStatement.setInt(4, cuatrimestre.getAnio());
			
			resultSet = preparedStatement.executeQuery();
			
			if (resultSet.next())
				resultado = true;
			
				
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}	
		return resultado;
	}

	@Override
	public void inscribir(Alumno alumno, Materia materia, Cuatrimestre cuatrimestre) {
		try {
			String queryString = "INSERT INTO cursa VALUES (?,?,?,?)";
			
			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			preparedStatement.setString(1, materia.getCodigo());
			preparedStatement.setInt(2, new Integer(alumno.getPadron()));
			preparedStatement.setInt(3, new Integer(cuatrimestre.getCuatrimestre()));
			preparedStatement.setInt(4, cuatrimestre.getAnio());
			
			preparedStatement.executeUpdate();
		
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean estaInscriptoEnMateria(String padron, String emailMateria, Cuatrimestre cuatrimestre) {
		Alumno alumno = this.getPorId(padron);
		Materia materia = MateriaDao.getInstance().getPorEmail(emailMateria);
		
		boolean resultado = false;
		
		if (materia != null && alumno != null)
			resultado = this.estaInscriptoEnMateria(alumno, materia, cuatrimestre);
		
		return resultado;
	}

	@Override
	public List<Materia> getMaterias(Alumno alumno) {
		List<Materia> listaMaterias = new ArrayList<Materia>();
		
		try {
			String queryString = "SELECT * FROM cursa WHERE padron=? AND cuatrimestre=? AND anio=?";
			
			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			preparedStatement.setInt(1, new Integer(alumno.getPadron()));
			preparedStatement.setInt(2, new Integer(FechaUtil.getCuatrimestreActual().getCuatrimestre()));
			preparedStatement.setInt(3, FechaUtil.getCuatrimestreActual().getAnio());
			resultSet = preparedStatement.executeQuery();
			
			Materia materiaBd;
			while (resultSet.next()) {
				materiaBd = MateriaDao.getInstance().getPorId(resultSet.getString("codigo_materia"));
				listaMaterias.add(materiaBd);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return listaMaterias;
	}
}
